<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post静态原始</title>
</head>
<body>
    <h1>post请求</h1>
    <form id="form">
        <input type="text" name="name">
        <input type="text" name="age">
        <button id="btn">提交内容</button>
    </form>
    <script>
        const oBtn  = document.getElementById('btn')
        const oForm = document.getElementById('form')
        const oName = document.querySelector('#form input[name=name]');
        const oAge = document.querySelector('#form input[name=age]');

        oForm.onsubmit = function(){
            // 获取用户输入信息
            const oNameMessage = oName.value
            const oAgeMessage = oAge.value

            //创建xhr实例对象
            const xhr = new XMLHttpRequest();
            //打开路径
            xhr.open('POST','/userPost',true)
            //发送请求

            // 设置请求头  来说明content-type类型
            xhr.setRequestHeader('Content-Type','application/JSON')
            xhr.send(JSON.stringify({
                name:oNameMessage,
                age:oAgeMessage
            }))

            //绑定事件
            xhr.onreadystatechange = function(){
                //判断状态码和响应码
                if(xhr.readyState === 4 && xhr.status>=200 && xhr.status<=299){
                    console.log(xhr.responseText);
                }

            }
            // 中断表单提交
            return false
        }
    </script>
</body>
</html>